<template>
  <div class="collection-management">
    <!-- 页面标题 -->
    <PageHeader 
      title="催款管理" 
      description="管理客户催款记录，跟踪催款进度"
      icon="Bell"
    />
    
    <!-- 数据管理模式切换 -->
    <el-tabs v-model="viewMode" class="view-mode-tabs">
      <el-tab-pane label="业务模式" name="business">
        <!-- 业务模式内容 -->
        <el-card class="main-card">
          <!-- 功能区域 -->
          <el-row :gutter="20" class="function-area">
            <el-col :span="16">
              <CollectionFilter 
                :query-params="queryParams"
                @update:query-params="updateQueryParams"
                @search="handleSearch"
                @reset="handleReset"
              />
            </el-col>
            <el-col :span="8">
              <div class="function-buttons">
                <el-button type="primary" @click="showAddDialog = true">
                  <el-icon><Plus /></el-icon>新增催款
                </el-button>
              </div>
            </el-col>
          </el-row>
          
          <!-- 催款记录表格 -->
          <CollectionTable
            :table-data="collectionRecords"
            :loading="loading"
            :pagination="pagination"
            :selected-records="selectedRecords"
            :show-advanced-filter="showAdvancedFilter"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            @sort-change="handleSortChange"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            @command="handleTableCommand"
          />
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="数据管理模式" name="data">
        <!-- 数据管理模式内容 -->
        <el-card class="main-card">
          <!-- 页面头部 -->
          <CollectionHeader 
            :stats="stats"
            :loading="loading"
            :capturing="capturing"
            :selected-records="selectedRecords"
            :view-mode="viewMode"
            :show-advanced-filter="showAdvancedFilter"
            @search="handleSearch"
            @reset="handleReset"
            @toggle-filter="showAdvancedFilter = !showAdvancedFilter"
            @view-mode-change="viewMode = $event"
            @showImportWizard="showImportDialog = true"
            @smart-filter="showFilterDialog = true"
            @show-batch-operations="showBatchDialog = true"
            @load-records="loadCollectionRecords"
            @export-records="handleExportRecords"
            @handle-smart-capture="handleSmartCapture"
          />
          
          <!-- 高级筛选 -->
          <CollectionFilterData 
            v-show="showAdvancedFilter"
            v-model="queryParams"
            @search="handleSearch"
            @reset="handleReset"
          />
          
          <!-- 智能建议 -->
          <SmartActions 
            v-if="showSmartActions"
            :smart-suggestions="smartSuggestions"
            :get-suggestion-type="getSuggestionType"
            @apply-suggestion="applySuggestion"
            @apply-all-suggestions="applyAllSuggestions"
            @remove-suggestion="removeSuggestion"
          />
          
          <!-- 催款记录表格 -->
          <CollectionTableData
            ref="collectionTableRef"
            v-model:query-params="queryParams"
            :table-data="tableData"
            :loading="loading"
            :pagination="{ page: queryParams.page, limit: queryParams.limit, total: total }"
            :selected-records="selectedRecords"
            :show-advanced-filter="showAdvancedFilter"
            @selection-change="handleSelectionChange"
            @view-detail="handleViewRecordDetail"
            @edit="handleEditRecordRemark"
            @refresh="loadCollectionRecords"
          />
          
          <!-- 分页 -->
          <CollectionPagination
            :model-value="{ page: queryParams.page, limit: queryParams.limit }"
            :total="total"
            @update:model-value="(val: { page: number; limit: number }) => { queryParams.page = val.page; queryParams.limit = val.limit }"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-card>
        
        <!-- 导入向导对话框 -->
        <CollectionImportWizardData 
          v-model="showImportDialog" 
          @import-success="handleImportSuccess"
        />
        
        <!-- 智能过滤设置抽屉 -->
        <SmartFilter 
          v-model="showFilterDialog" 
          @rules-updated="handleFilterRulesUpdated"
        />
        
        <!-- 批量操作面板 -->
        <BatchOperationPanel 
          v-model="showBatchDialog" 
          :selected-records="selectedRecords"
          @batch-action="handleBatchAction"
        />
        
        <!-- 催款记录详情对话框 -->
        <CollectionDetail
          v-model="showRecordDetailDialog"
          :record="currentRecord"
          @edit="handleEditRecordRemark"
        />
      </el-tab-pane>
    </el-tabs>
    
    <!-- 新增催款对话框 -->
    <CollectionAddDialog
      v-model="showAddDialog"
      @submit="handleAddRecord"
    />
    
    <!-- 编辑催款对话框 -->
    <CollectionEditDialog
      v-model="showEditDialog"
      :record-data="editingRecord"
      @submit="handleUpdateRecord"
    />
    
    <!-- 催款记录详情抽屉 -->
    <CollectionDetailDrawer
      v-model="detailDrawerVisible"
      :record-id="detailRecordId"
      @edit="handleEditRecord"
      @close="handleDetailDrawerClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import PageHeader from '@/components/layout/PageHeader.vue'

// 数据管理模式组件
import SmartActions from '@/views/finance/collection-data-components/components/SmartActions.vue'
import SmartFilter from '@/views/finance/collection-data-components/components/SmartFilter.vue'
import BatchOperationPanel from '@/views/finance/collection-data-components/components/BatchOperationPanel.vue'
import CollectionFilterData from '@/views/finance/collection-data-components/components/CollectionFilter.vue'
import CollectionTableData from '@/views/finance/collection-data-components/components/CollectionTable.vue'
import CollectionDetail from '@/views/finance/collection-data-components/components/CollectionDetail.vue'
import CollectionImportWizardData from '@/views/finance/collection-data-components/components/CollectionImportWizard.vue'
import CollectionHeader from '@/views/finance/collection-data-components/components/CollectionHeader.vue'
import CollectionPagination from '@/views/finance/collection-data-components/components/CollectionPagination.vue'

// 业务模式组件（使用数据管理模式组件作为替代）
import CollectionFilter from '@/views/finance/collection-data-components/components/CollectionFilter.vue'
import CollectionTable from '@/views/finance/collection-data-components/components/CollectionTable.vue'
import CollectionAddDialog from '@/views/finance/collection-data-components/components/CollectionImportWizard.vue'
import CollectionEditDialog from '@/views/finance/collection-data-components/components/CollectionImportWizard.vue'
import CollectionDetailDrawer from '@/views/finance/collection-data-components/components/CollectionDetail.vue'

interface CollectionQueryParams {
  customerName: string
  collectionMethod: string
  collectionResult: string
  dateRange: string[]
  page: number
  limit: number
}

interface CollectionRecord {
  id: string
  orderInfo: {
    platformOrderId: string
    amount: number
    orderDate: string
  }
  customerInfo: {
    name: string
    contactPerson: string
    phone: string
    email: string
  }
  collectionInfo: {
    collectionId: string
    method: string
    duration: number
    result: string
    collectionTime: string
    operator: string
    notes: string
    isBatch: boolean
    nextFollowupDate: string
    satisfactionScore: number
  }
}

interface CollectionStats {
  totalRecords: number
  pendingRecords: number
  completedRecords: number
  thisMonthRecords: number
  successRate: number
  avgCollectionDays: number
}

// 视图模式
const viewMode = ref('business')

// 数据管理模式相关数据
const showAdvancedFilter = ref(false)
const capturing = ref(false)
const smartSuggestions = ref<any[]>([])
const filterRules = ref<any[]>([])
const currentRecordId = ref('')
const currentRecord = ref<any>(null)
const showRecordDetailDialog = ref(false)
const showImportDialog = ref(false)
const showFilterDialog = ref(false)
const showBatchDialog = ref(false)
const tableData = ref<any[]>([])
const total = ref(0)
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const detailDrawerVisible = ref(false)
const detailRecordId = ref('')
const collectionTableRef = ref()

// 计算属性
const showSmartActions = computed(() => smartSuggestions.value.length > 0)

// 响应式数据
const collectionRecords = ref<CollectionRecord[]>([])
const loading = ref(false)
const selectedRecords = ref<CollectionRecord[]>([])
const stats = ref<CollectionStats>({
  totalRecords: 0,
  pendingRecords: 0,
  completedRecords: 0,
  thisMonthRecords: 0,
  successRate: 0,
  avgCollectionDays: 0
})

// 查询参数
const queryParams = reactive<CollectionQueryParams>({
  customerName: '',
  collectionMethod: '',
  collectionResult: '',
  dateRange: [],
  page: 1,
  limit: 20
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 方法
const loadCollectionRecords = async () => {
  loading.value = true
  try {
    // 模拟API调用
    setTimeout(() => {
      collectionRecords.value = [
        {
          id: '1',
          orderInfo: {
            platformOrderId: 'PO2023001',
            amount: 15000.00,
            orderDate: '2023-01-15'
          },
          customerInfo: {
            name: '测试客户A',
            contactPerson: '张三',
            phone: '13800138000',
            email: 'zhangsan@test.com'
          },
          collectionInfo: {
            collectionId: 'COL000001',
            method: 'phone',
            duration: 15,
            result: '已联系客户，承诺3月底付款',
            collectionTime: '2023-03-01',
            operator: '李四',
            notes: '客户资金紧张，需分期付款',
            isBatch: false,
            nextFollowupDate: '2023-03-15',
            satisfactionScore: 4
          }
        }
      ]
      pagination.total = 1
      
      // 模拟统计数据
      stats.value = {
        totalRecords: 150,
        pendingRecords: 25,
        completedRecords: 125,
        thisMonthRecords: 8,
        successRate: 85.5,
        avgCollectionDays: 12.3
      }
      
      loading.value = false
    }, 500)
  } catch (error) {
    ElMessage.error('加载催款记录失败')
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadCollectionRecords()
}

const handleReset = () => {
  Object.assign(queryParams, {
    customerName: '',
    collectionMethod: '',
    collectionResult: '',
    dateRange: []
  })
  pagination.page = 1
  loadCollectionRecords()
}

const updateQueryParams = (params: CollectionQueryParams) => {
  Object.assign(queryParams, params)
}

const handleSelectionChange = (selection: CollectionRecord[]) => {
  selectedRecords.value = selection
}

const handleRowClick = (row: CollectionRecord) => {
  detailRecordId.value = row.id
  detailDrawerVisible.value = true
}

const handleSortChange = (sort: any) => {
  // 处理排序
  console.log('排序:', sort)
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  loadCollectionRecords()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadCollectionRecords()
}

const handleTableCommand = (command: string, row: CollectionRecord) => {
  switch (command) {
    case 'edit':
      handleRowClick(row)
      break
    case 'delete':
      handleDeleteRecord(row)
      break
    case 'detail':
      detailRecordId.value = row.id
      detailDrawerVisible.value = true
      break
  }
}

const handleExportRecords = () => {
  // 处理导出
  ElMessage.info('导出功能开发中')
}

const handleSmartCapture = () => {
  capturing.value = true
  // 智能抓取的逻辑
  setTimeout(() => {
    capturing.value = false
    ElMessage.success('智能抓取完成')
    // 重新加载数据
    loadCollectionRecords()
  }, 2000)
}

const handleImportSuccess = () => {
  loadCollectionRecords()
  ElMessage.success('导入成功')
}

const editingRecord = ref<CollectionRecord | null>(null)

const handleAddRecord = async (data: any) => {
  try {
    // 模拟API调用
    setTimeout(() => {
      showAddDialog.value = false
      loadCollectionRecords()
      ElMessage.success('新增成功')
    }, 500)
  } catch (error) {
    ElMessage.error('新增失败')
  }
}

const handleUpdateRecord = async (data: any) => {
  try {
    // 模拟API调用
    setTimeout(() => {
      showEditDialog.value = false
      loadCollectionRecords()
      ElMessage.success('更新成功')
    }, 500)
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const handleDeleteRecord = async (row: CollectionRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除该催款记录吗？', '提示', {
      type: 'warning'
    })
    
    // 模拟API调用
    setTimeout(() => {
      loadCollectionRecords()
      ElMessage.success('删除成功')
    }, 500)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleDetailDrawerClose = () => {
  detailDrawerVisible.value = false
}

const handleEditRecord = (record: CollectionRecord) => {
  detailDrawerVisible.value = false
  editingRecord.value = record
  showEditDialog.value = true
}

// 数据管理模式方法
const loadSmartSuggestions = async () => {
  // 模拟加载智能建议
  smartSuggestions.value = [
    {
      id: '1',
      type: 'followup',
      description: '建议跟进3条即将到期的催款记录',
      records: ['1', '2', '3'],
      confidence: 92
    }
  ]
}

// 获取建议类型的方法
const getSuggestionType = (type: string) => {
  const typeMap: Record<string, string> = {
    followup: 'warning',
    priority: 'success',
    duplicate: 'info'
  }
  return typeMap[type] || 'info'
}

// 应用所有建议
const applyAllSuggestions = () => {
  ElMessageBox.confirm('确定要应用所有智能建议吗？', '应用所有建议', {
    type: 'warning'
  }).then(() => {
    // 应用所有建议的逻辑
    ElMessage.success('所有建议已应用')
    // 重新加载数据
    loadCollectionRecords()
  }).catch(() => {
    // 取消应用
  })
}

// 移除建议
const removeSuggestion = (suggestionId: string) => {
  smartSuggestions.value = smartSuggestions.value.filter((s: any) => s.id !== suggestionId)
}

const handlePageChange = (page: number) => {
  queryParams.page = page
  loadCollectionRecords()
}

const handlePageSizeChange = (size: number) => {
  queryParams.limit = size
  queryParams.page = 1
  loadCollectionRecords()
}

const applySuggestion = (suggestion: any) => {
  ElMessageBox.confirm(`确定要应用建议"${suggestion.description}"吗？`, '应用建议', {
    type: 'warning'
  }).then(() => {
    // 应用建议的逻辑
    ElMessage.success('建议已应用')
    // 重新加载数据
    loadCollectionRecords()
  }).catch(() => {
    // 取消应用
  })
}

const handleViewRecordDetail = (record: any) => {
  currentRecord.value = record
  showRecordDetailDialog.value = true
}

const handleEditRecordRemark = (record: any) => {
  // 编辑备注的逻辑
  ElMessage.success('备注已更新')
}

const handleFilterRulesUpdated = (rules: any[]) => {
  filterRules.value = rules
  ElMessage.success('过滤规则已更新')
  // 重新加载数据
  loadCollectionRecords()
}

const handleBatchAction = (action: string, data: any) => {
  ElMessage.success(`批量操作"${action}"执行成功`)
  // 重新加载数据
  loadCollectionRecords()
}

// 生命周期
onMounted(() => {
  loadCollectionRecords()
  loadSmartSuggestions()
})
</script>

<style scoped lang="scss">
.collection-management {
  padding: 20px;
}

.function-area {
  margin-bottom: 20px;
}

.function-buttons {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
}

.main-card {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .collection-management {
    padding: 12px;
  }
  
  .function-area {
    margin-bottom: 16px;
  }
}
</style>